package com.koron.configure.defectlevel.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.datadict.bean.po.SysDataDictDetail;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.StringUtils;
import com.koron.configure.defectlevel.bean.DefectLevelAddDto;
import com.koron.configure.defectlevel.bean.DefectLevelBean;
import com.koron.configure.defectlevel.mapper.DefectLevelMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@Api(tags = "缺陷等级配置")
@RestController
@RequestMapping("/defectlevel")
public class DefectLevelController {

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }


    @ApiOperation(value = "缺陷等级配置-列表")
    @GetMapping("queryList")
    public Response<List> queryList() {
        String currDs = getCurrDs();
        List<DefectLevelAddDto> list = ADOConnection.runTask(getCurrDs(), factory -> {
            //数据字典
            List<SysDataDictDetail> sjzdlist = CodeTools.getDictSortByClassCode("workorderManagement", "defect_order_level");
            List<DefectLevelAddDto> dblist = factory.getMapper(DefectLevelMapper.class).queryAllById(null);//数据库相应数据字典的数据
            List<DefectLevelAddDto> temlist = new ArrayList<>();
            for (SysDataDictDetail tem : sjzdlist) {
                Optional<DefectLevelAddDto> first = dblist.stream().filter(d -> d.getLevel().equals(tem.getKey())).findFirst();
                DefectLevelAddDto dto = first.orElse(new DefectLevelAddDto(tem.getKey(), Integer.valueOf("0")));
                dto.setSort(tem.getSort());//伍哥建议：跟数据字典顺序保持一直
                temlist.add(dto);
            }
            return temlist;
        }, List.class);
        return Response.ok(list);
    }

    @ApiOperation(value = "外部调用-查消缺天数-列表")
    @GetMapping("queryAllByLevel")
    public Response<List<DefectLevelAddDto>> queryAllByLevel(@RequestParam(value = "level",required = false) String level) {
        List<DefectLevelAddDto> dto = ADOConnection.runTask(getCurrDs(), factory -> {
            DefectLevelMapper mapper = factory.getMapper(DefectLevelMapper.class);
            if(StrUtil.isNotBlank(level)){
                return mapper.queryAllByLevel(level);
            }else{
                return mapper.queryAll();
            }
        }, List.class);
        return Response.ok(dto);
    }



    @ApiOperation(value = "缺陷等级配置-新建 (原型调整-已废弃）")
    @GetMapping("addlevel")
    public Response<String> addlevel(DefectLevelAddDto dto) {

        //获取字典里所有工作票类型
        Map<String, String> dicmap = CodeTools.getDictByClassCode("workorderManagement", "defect_order_level");
        Set<String> keySet = dicmap.keySet();
        Assert.isFalse(!keySet.contains(dto.getLevel()), "没该工作票类型");

        List<DefectLevelAddDto> list = Optional.ofNullable(ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(DefectLevelMapper.class).queryAllById(null);
        }, List.class)).orElse(new ArrayList());

        if (StringUtils.isNotEmpty(list)) {
            List<String> allLevel = list.stream().map(DefectLevelAddDto::getLevel).collect(Collectors.toList());
            Assert.isFalse(allLevel.contains(dto.getLevel()), "缺陷等级不可以重复添加");
        }

        String id = ADOConnection.runTask(getCurrDs(), factory -> {
            String temId = CodeTools.getCode32();
            Integer sort = list.size() == 0 ? 1 : list.size() + 1;
            DefectLevelBean bean = Convert.convert(DefectLevelBean.class, dto);
            bean.setSort(sort);
            bean.setId(temId);
            factory.getMapper(DefectLevelMapper.class).insertSelective(bean);
            return temId;
        }, String.class);

        return Response.ok(id);
    }

    @ApiOperation(value = "缺陷等级配置-更新")
    @GetMapping("updatelevel")
    public Response<String> updatelevel(DefectLevelAddDto dto) {

        if (StringUtils.isEmpty(dto.getId())) {
            String id = ADOConnection.runTask(getCurrDs(), factory -> {
                String temId = CodeTools.getCode32();
                DefectLevelBean bean = Convert.convert(DefectLevelBean.class, dto);
                bean.setId(temId);
                factory.getMapper(DefectLevelMapper.class).insertSelective(bean);
                dto.setId(temId);
                return temId;
            }, String.class);
        }else{
            ADOConnection.runTask(getCurrDs(), factory -> {
                DefectLevelBean bean = Convert.convert(DefectLevelBean.class, dto);
                factory.getMapper(DefectLevelMapper.class).updateByPrimaryKeySelective(bean);
                return null;
            }, void.class);
        }


        return Response.ok(dto.getId());
    }


    @ApiOperation(value = "缺陷等级配置-删除 (原型调整-已废弃）")
    @DeleteMapping("deleteById")
    public Response<Integer> deleteById(@RequestParam(value = "id") String id) {
        Integer delflag = ADOConnection.runTask(getCurrDs(), factory -> {
            int i = factory.getMapper(DefectLevelMapper.class).deleteByPrimaryKey(id);
            return i;
        }, Integer.class);
        return Response.ok(delflag);
    }

    @ApiOperation(value = "根据缺陷id等级判断是否为一类缺陷")
    @GetMapping("getDefectLevelByLevel")
    public Response<Boolean> getDefectLevelByKeyAndValue(@RequestParam(value = "level") String level) {
        DefectLevelBean defectLevelBean = ADOConnection.runTask(getCurrDs(), factory -> {
            DefectLevelBean levelBean = factory.getMapper(DefectLevelMapper.class).getDefectLevelByLevel(level);
            return levelBean;
        }, DefectLevelBean.class);
        return Response.ok(defectLevelBean == null ? false : (defectLevelBean.getFirstClass() == 1 ? true : false));
    }

}
